package com.deyuanyun.pic.pbf.aop;

import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.pbf.domain.RepairTask;
import com.deyuanyun.pic.pbf.domain.RepairTaskWorkload;
import com.deyuanyun.pic.settings.aop.BasePushMsgAspect;
import com.deyuanyun.pic.settings.service.msgtemplate.AbstractPushMsgTemplate;
import com.deyuanyun.pic.settings.service.msgtemplate.PushMessage;
import com.deyuanyun.pic.settings.service.msgtemplate.pbf.RepairProjectPushMsg;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 维修维护项目启动，结束的切面
 *
 * @author axiao(xj08.dream@gmail.com)
 * @version 1.0 Histroy: [修改人][时间][描述]
 * @date 2016-08-12
 */
@Aspect
@Service
public class RepairTaskAspect extends BasePushMsgAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepairTaskAspect.class);

    /**
     * 维修项目切入点
     * @param
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    @Pointcut(value = "@annotation(pushMessage) && target(com.deyuanyun.pic.pbf.service.RepairTaskService)")
    private void repairTaskServicePointcut(PushMessage pushMessage) {

    }

    /**
     * 在{@link com.deyuanyun.pic.pbf.service.RepairTaskService#updateDataStated(String[], com.deyuanyun.pic.pbf.enumeration.DefectStateEnum)}方法执行之后织入，进行消息推送
     * @param 
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    @AfterReturning(value = "repairTaskServicePointcut(pushMessage) && execution(* updateDataStated(..))", returning = "retVal")
    public void updateDataStatedAdvice(JoinPoint joinPoint, PushMessage pushMessage, int retVal) {
        try{
            if(retVal > 0) {
                SpelExpressionParser parser =  new SpelExpressionParser();
                EvaluationContext context = super.getEvaluationContext(joinPoint);
                String[] values = pushMessage.value();
                if(values.length > 0) {
                    String[] rtIds = (String[]) parser.parseExpression(values[0]).getValue(context);
                    LOGGER.info("多个维修任务点击发布,得到的维修任务有：" + rtIds.length + "条");
                    String state = parser.parseExpression(values[1]).getValue(context, String.class);
                    if ("state20".equals(state)) { //当是发布的时候，为项目启动
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put(RepairProjectPushMsg.REPAIR_IDS, rtIds);
                        map.put(RepairProjectPushMsg.REPAIR_FLAG, "已启动");
                        pushMsg(map);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("维修项目消息推送异常", e);
        }
    }

    /**
     * 在{@link com.deyuanyun.pic.pbf.service.RepairTaskService#updateRepairTaskStated(String[], com.deyuanyun.pic.pbf.enumeration.RepairTaskStatedEnum)}方法执行之后织入，进行消息推送
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    @AfterReturning(value = "repairTaskServicePointcut(pushMessage) && execution(* updateRepairTaskStated(..))", returning = "retVal")
    public void updateRepairTaskStatedAdvice(JoinPoint joinPoint, PushMessage pushMessage, int retVal) {
        try {
            if(retVal > 0) {
                SpelExpressionParser parser =  new SpelExpressionParser();
                EvaluationContext context = super.getEvaluationContext(joinPoint);
                String[] values = pushMessage.value();
                if(values.length > 0) {
                    String[] rtIds = (String[]) parser.parseExpression(values[0]).getValue(context);
                    LOGGER.info("多个维修任务点击已维修,得到的维修任务有：" + rtIds.length + "条");
                    String taskStatedEnum = parser.parseExpression(values[1]).getValue(context, String.class);
                    if ("ALREADY_REPAIR".equals(taskStatedEnum)) { //当是已维修的时候，为项目关闭
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put(RepairProjectPushMsg.REPAIR_IDS, rtIds);
                        map.put(RepairProjectPushMsg.REPAIR_FLAG, "已关闭");
                        pushMsg(map);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("维修项目消息推送异常", e);
        }
    }

    /**
     * 在{@link com.deyuanyun.pic.pbf.service.RepairTaskService#createOrUpdate(RepairTask, RepairTaskWorkload, String[])}方法执行之后织入，进行消息推送
     * @param
     * @return
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    @AfterReturning(value = "repairTaskServicePointcut(pushMessage) && execution(* createOrUpdate(..))")
    public void createOrUpdateAdvice(JoinPoint joinPoint, PushMessage pushMessage) {
        try {
            SpelExpressionParser parser =  new SpelExpressionParser();
            EvaluationContext context = super.getEvaluationContext(joinPoint);
            String[] values = pushMessage.value();
            if(values.length > 0) {
                String repairTaskId = parser.parseExpression(values[0]).getValue(context, String.class);
                String dataStated = parser.parseExpression(values[1]).getValue(context, String.class);
                if (StringUtils.isNotEmpty(repairTaskId) && StringUtils.isNotEmpty(dataStated)) {
                    if("20".equals(dataStated)) { //当是发布的时候，为项目启动
                        LOGGER.info("单个维修项目发布");
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put(RepairProjectPushMsg.REPAIR_IDS, new String[]{ repairTaskId });//取到维修任务id并放入到map中
                        map.put(RepairProjectPushMsg.REPAIR_FLAG, "已启动");
                        pushMsg(map);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("维修项目消息推送异常", e);
        }
    }

    /**
     * 推送消息
     * @param map
     * @return 
     * @author axiao(xj08.dream@gmail.com)
     * @date 2016-10-09
     */
    private void pushMsg(Map<String, Object> map) {
        //当map不为空的时候调用接口推送消息
        if (map != null && !map.isEmpty()) {
            LOGGER.info("开始推送消息");
            AbstractPushMsgTemplate repairProjectPushMsg = new RepairProjectPushMsg();
            repairProjectPushMsg.setInterface(false, map);
            repairProjectPushMsg.pushMsg();
        }
    }

}
